<template>
  <div>
    <el-dialog
      top="5vh"
      width="55%"
      :title="dialogType === 'add' ? '新增' : '编辑'"
      destroy-on-close
      append-to-body
      fullscreen
      v-if="visible"
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="handleEditReset"
    >
      <div class="dialog-content">
        <avue-form ref="editForm" :option="option" v-model="form" @submit="handSaveConfig">
          <template slot-scope="{}" slot="automatic">
            <label>备注：自动报检的触发时机在【参数管理】中进行配置</label>
          </template>
          <template slot-scope="{}" slot="ruleControl">
            <h3>1. 防漏检验控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
            <div class="ml20">
              <el-radio v-model="form.missingInspectControl" :label="1">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许成品入库，仅预警提示告知
              </el-radio>

              <span>备注：具体到预警中心设计</span>
            </div>
            <div class="mt20 ml20 rules-container">
              <el-radio v-model="form.missingInspectControl" :label="2" size="medium">
                <el-tooltip content="待检单达到设定的漏检时长控制时" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                不允许成品入库
              </el-radio>
              <template slot-scope="{}" slot="colseControl">
                <h3>3. 检验时长控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
              </template>
            </div>
          </template>
          <template slot-scope="{}" slot="nGControl">
            <h3>2. 检验结果为NG控制</h3>
            <div class="ml20">
              <el-radio v-model="form.resultNgControl" :label="1">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许成品入库，仅预警提示告知
              </el-radio>
              <span>备注：具体到预警中心设计</span>
            </div>
            <div class="mt20 ml20 rules-container">
              <el-radio v-model="form.resultNgControl" :label="2" size="medium">
                <el-tooltip
                  content="待检单达到设定的漏检时长控制时，若是工单首件，该工单每个生产工序都无法过站并提示； 若是工段首件，则该工段内的每个工序无法过站并提示！"
                  placement="top"
                >
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                不允许成品入库
              </el-radio>
            </div>
          </template>
          <template slot-scope="{}" slot="nGControl1">
            <h3>3. 检验结果为NG，但不良处理不为让步通过时（即为二次检/返工）控制<span style="color: #f56c6c; margin-right: 4px">*</span></h3>
            <div class="ml20">
              <el-radio v-model="form.resultNgHandingControl" :label="1">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许出库，仅预警提示告知
              </el-radio>
              <span>备注：具体到预警中心设计</span>
            </div>
            <div class="mt20 ml20 rules-container">
              <el-radio v-model="form.resultNgHandingControl" :label="2" size="medium">
                <el-tooltip content="待检单结果为NG，不良处理的结果不为让步通过时，则该检验单的不良处理不为让步通过时，则不能出库；若为让步通过，则允许出库" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                不允许出库
              </el-radio>
            </div>
          </template>
          <template slot-scope="{}" slot="nGControl2">
            <h3>4. 不良包装入库控制</h3>
            <div class="ml20">
              <el-radio v-model="form.inboundControl" :label="1">
                <el-tooltip content="在预警中心设置若待检单的未处理时长达到设定值时，则会预警消息通知" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                允许出库，仅预警提示告知
              </el-radio>
              <span>备注：具体到预警中心设计</span>
            </div>
            <div class="mt20 ml20 rules-container">
              <el-radio v-model="form.inboundControl" :label="2" size="medium">
                <el-tooltip content="检验时不良登记某个包装后，则该包装无法进行出库！但不良处理后，则可进行入库" placement="top">
                  <i class="el-tooltip el-icon-info"></i>
                </el-tooltip>
                不允许出库
              </el-radio>
            </div>
          </template>
          <template slot-scope="{}" slot="colseControl">
            <label><span style="color: #f56c6c; margin-right: 4px">*</span>检验时长控制 : </label>
          </template>
          <template slot-scope="{}" slot="avueCurd">
            <div class="avue-table">
              <avue-crud ref="editCrud" v-model="tableForm" :option="tableOption" :data="form.qmsInspectionPlanObjectVOList" @row-update="addUpdate" @row-del="rowDel">
                <template slot="menuLeft">
                  <el-button type="primary" size="small" icon="el-icon-plus" @click="handleAddRows">新 增</el-button>
                  <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
                </template>
              </avue-crud>
            </div>
          </template>
        </avue-form>
      </div>
      <span slot="footer">
        <el-button size="small" type="primary" icon="el-icon-check" @click="handleEditSubmit">保存</el-button>
        <el-button size="small" icon="el-icon-delete" @click="handleEditReset">取消</el-button>
      </span>
    </el-dialog>
    <importDialogComp
      title="适用对象导入"
      url="/api/mes-product/qms-inspection-planconfig/import-cqc-plan-object"
      export-name="完工检验适用对象导入模板.xlsx"
      :form-data="fromData"
      :is-form-data-json="true"
      :visible.sync="showImportDialog"
      @submit="codeClose"
    ></importDialogComp>
    <global-modal-template
      ref="commonModalTemplate"
      :visibile.sync="selectDialogVisiable"
      :option="dialogOption"
      @getSelectedRows="getSelectedRows"
      :key="timer"
      @newKey="newKey"
    >
    </global-modal-template>
  </div>
</template>

<script>
import importDialogComp from '@/components/dialog/import';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { getPlanConfigDetail, savePlanConfig } from '@/api/quality/palnConfig';
import { filterEmptyValues } from '@/util/util';
export default {
  name: 'editFinishPlanConfig',
  components: {
    importDialogComp,
    GlobalModalTemplate
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: '编辑'
    },
    dialogType: {
      type: String,
      default: 'add'
    }
  },

  data() {
    return {
      isValid: true,
      tableForm: {},
      selectDialogVisiable: false,
      selectRow: [],
      showImportDialog: false,
      timer: new Date().getTime(),
      modalName: '',
      option: {
        searchShow: true,
        searchMenuSpan: 6,
        menuPosition: 'right',
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 150,
        group: [
          {
            label: '基本信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '计划名称',
                prop: 'planName',
                span: 8,
                rules: [{ required: true, message: '请输入计划名称', trigger: 'blur' }]
              },
              {
                label: '计划编码',
                prop: 'planNo',
                disabled: true,
                span: 8
              },
              {
                label: '检验类型',
                prop: 'planType',
                value: '完工检验',
                disabled: true,
                span: 8
              }
            ]
          },
          {
            label: '报检方式',
            prop: 'equipmentInfo1',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '报检方式',
                prop: 'sendExamineType',
                multiple: true,
                dicData: [
                  { label: '自动', value: 'AUTO' },
                  { label: '手动', value: 'MANUAL' }
                ],
                span: 8,
                labelTip: '选择手动或自动后，则表示生成的待检单会受防呆规则内容的受控',
                type: 'select',
                rules: [{ required: true, message: '请选择报检方式', trigger: 'change' }]
              },
              {
                prop: 'automatic',
                labelWidth: 0,
                span: 8,
                formslot: true
              }
            ]
          },
          {
            label: '异常处理流程设置',
            prop: 'equipmentInfo3',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '检验结果为NG，需进行不良处理',
                prop: 'resultNgIsHandingControl',
                type: 'radio',
                labelWidth: 220,
                span: 24,
                value: 1,
                dicData: [
                  {
                    label: '是',
                    value: 1
                  },
                  {
                    label: '否',
                    value: 2
                  }
                ]
              }
            ]
          },
          {
            label: '防呆规则',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'ruleControl',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              },
              {
                prop: 'nGControl',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              },
              {
                prop: 'nGControl1',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              },
              {
                prop: 'nGControl2',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              }
            ]
          },
          {
            label: '关闭控制',
            prop: 'equipmentInfo2',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'colseControl',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              },
              {
                label: '未检时间(min)',
                type: 'number',
                min: 0,
                precision: 0,
                prop: 'closeInspectDuration',
                labelWidth: 150,
                span: 6,
                rules: [{ required: true, message: '请输入未检时间', trigger: 'blur' }],
                control: (val, form) => {
                  return {
                    closeInspectDuration: { disabled: this.isDisable }
                  };
                }
              }
            ]
          },
          {
            label: '适用对象',
            prop: 'equipmentInfo4',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                prop: 'avueCurd',
                labelWidth: 0,
                span: 24,
                order: 6,
                formslot: true
              }
            ]
          }
        ]
      },
      form: {
        planType: '完工检验',
        qmsInspectionPlanObjectVOList: []
      },
      tableOption: {
        height: '400px',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        filterBtn: false,
        refreshBtn: false,
        columnBtn: false,
        border: true,
        index: true,
        indexLabel: '序号',
        searchMenuSpan: 6,
        searchLabelWidth: 90,
        rowKey: 'spec',
        viewBtn: false,
        delBtn: true,
        editBtn: true,
        addBtn: false,
        labelWidth: 130,
        selection: true,
        highlightCurrentRow: true, // 选中高亮
        dialogClickModal: false,
        searchMenuPosition: 'right',
        searchSpan: 6,
        column: [
          {
            label: '产品编码',
            prop: 'partNo',
            type: 'search',
            readonly: true,
            span: 24,
            appendClick: () => {
              this.openPartModal('editPartModel');
            }
          },
          {
            label: '产品名称',
            prop: 'partName',
            span: 24,
            disabled: true
          }
        ]
      },
      dialogOption: {}
    };
  },
  computed: {
    fromData() {
      return { inspectType: 'CQC' };
    }
  },
  methods: {
    async getDetail(id) {
      try {
        const res = await getPlanConfigDetail({ id: id });
        const data = res.data.data;
        const options = JSON.parse(data.options);
        delete data.options;
        const sendExamineType = data.sendExamineType ? data.sendExamineType.split(',') : [];
        this.form = {
          ...data,
          ...options,
          sendExamineType
        };
      } catch (e) {
        console.warn(e);
      }
    },
    handleEditReset() {
      this.$refs.editForm.resetForm();
      this.form = {
        planType: '完工检验',
        qmsInspectionPlanObjectVOList: []
      };
      this.$emit('update:visible', false);
      this.$emit('closeDialog');
    },
    handleEditSubmit() {
      this.$refs.editForm.submit();
    },
    async handSaveConfig(form, done) {
      if (!this.form.qmsInspectionPlanObjectVOList || !this.form.qmsInspectionPlanObjectVOList.length) {
        this.$message.error('请选择适用对象');
        done();
        return;
      }
      if (!this.form.missingInspectControl) {
        this.$message.error('请选择防漏检验控制');
        done();
        return;
      }
      if (!this.form.resultNgControl) {
        this.$message.error('请选择检验结果为NG时控制');
        return;
      }
      if (!this.form.resultNgHandingControl) {
        this.$message.error('请选择检验结果为NG，但不良处理不为让步通过时（即为二次检/返工）控制');
        done();
        return;
      }
      if (!this.form.inboundControl) {
        this.$message.error('请选择不良产品入库控制');
        done();
        return;
      }
      const formData = filterEmptyValues(this._cloneDeep(this.form));
      const options = {
        missingInspectControl: formData.missingInspectControl,
        resultNgHandingControl: formData.resultNgHandingControl,
        resultNgControl: formData.resultNgControl,
        inboundControl: formData.inboundControl,
        closeInspectDuration: form.closeInspectDuration,
        resultNgIsHandingControl: formData.resultNgIsHandingControl
      };
      const params = {
        id: formData.id,
        options: JSON.stringify(options),
        inspectType: 'CQC',
        inspectSubType: '',
        planNo: formData.planNo,
        planName: formData.planName,
        sendExamineType: formData.sendExamineType.join(','),
        remark: '',
        qmsInspectionPlanObjectVOList: formData.qmsInspectionPlanObjectVOList
      };
      try {
        const res = await savePlanConfig(params);
        this.$message.success('保存成功');
        this.$refs.editForm.resetForm();
        this.form = {
          planType: '完工检验',
          qmsInspectionPlanObjectVOList: []
        };
        this.$emit('update:visible', false);
        this.$emit('closeDialog');
      } catch (e) {
        console.log(e);
      } finally {
        done();
      }
    },
    handleImport() {
      this.showImportDialog = true;
    },
    handleAddRows() {
      this.openPartModal('partModal');
    },
    codeClose(value, data) {
      if (value) {
        const qmsInspectionPlanObjectVOList = this.form.qmsInspectionPlanObjectVOList || [];
        qmsInspectionPlanObjectVOList.push(...data);
        console.log(qmsInspectionPlanObjectVOList);
        // this.form.qmsInspectionPlanObjectVOList = qmsInspectionPlanObjectVOList;
        this.$set(this.form, 'qmsInspectionPlanObjectVOList', qmsInspectionPlanObjectVOList);
      }
    },

    rowDel(row, index) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.qmsInspectionPlanObjectVOList.splice(index, 1);
      });
    },
    addUpdate(form, index, done, loading) {
      const qmsInspectionPlanObjectVOList = this._cloneDeep(this.form.qmsInspectionPlanObjectVOList) || [];
      qmsInspectionPlanObjectVOList.splice(index, 1);
      const tableData = qmsInspectionPlanObjectVOList.concat(this.selectRow);
      this.$set(this.form, 'qmsInspectionPlanObjectVOList', tableData);
      this.selectRow = [];
      done();
    },

    judgeIsRepeat(qmsInspectionPlanObjectVOList, selectRow) {
      const resultRecords = [];
      const recordsMap = new Map();
      const resultMap = new Map();
      //  将已有数据 生成map{partnerId:{ partnerId, partnerName, partNos: [] }}
      for (const record of qmsInspectionPlanObjectVOList) {
        const { partnerId, partNo, partnerName } = record;

        if (!recordsMap.has(partnerId)) {
          recordsMap.set(partnerId, { partnerId, partnerName, partNos: [] });
        }
        recordsMap.get(partnerId).partnerName = partnerName;
        recordsMap.get(partnerId).partNos.push(partNo);
      }
      // 选择后的数据 如果 partnerId 相等则判断其物料编码是否已经存在与已选数据中 如果存在则把其相关信息存入 resultMap
      for (const select of selectRow) {
        const { partnerId, partNo, partnerName } = select;
        if (recordsMap.has(partnerId)) {
          const partNos = recordsMap.get(partnerId).partNos;
          if (partNos.includes(partNo)) {
            resultMap.set(partnerId, { partnerId, partnerName, partNos: [] });
            resultMap.get(partnerId).partNos.push(partNo);
          }
        }
      }
      // 整理 resultMap返回格式
      for (const record of resultMap.values()) {
        const partNos = record.partNos;
        resultRecords.push({ partnerId: record.partnerId, partnerName: record.partnerName, partNos });
      }
      return { isRepeat: resultRecords.length, result: resultRecords };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'partModal':
          const selectData = rowData.map((item) => ({
            partNo: item.code,
            partName: item.name,
            partMasterId: item.id
          }));
          const qmsInspectionPlanObjectVOList = this._cloneDeep(this.form.qmsInspectionPlanObjectVOList) || [];
          const data = qmsInspectionPlanObjectVOList.concat(selectData);
          this.$set(this.form, 'qmsInspectionPlanObjectVOList', data);
          break;
        case 'editPartModel':
          const tableForm = {
            partNo: rowData.map((i) => i.code).join(','),
            partName: rowData.map((i) => i.name).join(',')
          };
          this.selectRow = rowData.map((item) => ({
            partNo: item.code,
            partName: item.name,
            partId: item.id
          }));
          this.tableForm = tableForm;
          break;
      }
    },
    openPartModal(modalName) {
      this.modalName = modalName;
      this.dialogOption = {
        selection: modalName,
        modalTitle: '物料数据（双击进行选择）',
        url: `/api/mes-product/qms-inspection-planconfig/query-page-cqc-unUsed-partMasterVO`,
        isPage: true,
        index: false,
        columnDefs: [
          {
            label: '物料编码',
            prop: 'code',
            search: true
          },
          {
            label: '物料名称',
            prop: 'name',
            search: true
          }
        ],
        selectable: (row, index) => {
          return !this.form.qmsInspectionPlanObjectVOList.map((item) => item.partNo).includes(row['code']);
        },
        selectionArray: this.form.qmsInspectionPlanObjectVOList.map((item) => item.partNo) || [],
        isToggleSelection: true,
        filterKey: 'code'
      };
      this.selectDialogVisiable = true;
    },

    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.dialog-content {
  height: calc(100vh - 180px);
  overflow-y: scroll;
  h3 {
    margin: 0;
    font-size: 15px;
  }
  .mt20 {
    margin-top: 20px;
  }
  .ml20 {
    margin-left: 20px;
  }
  .rules-container {
    display: flex;
    align-items: center;
    height: 32px;
  }
  .num-input-contain {
    label {
      position: relative;
    }
    color: #606266;
  }
  .input-width {
    width: 300px;
  }
  .invalid-input {
    ::v-deep .el-input__inner {
      border: 1px solid #f56c6c;
    }
  }
  .invalid-span {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1;
    padding-top: 4px;
    position: relative;
    top: 25px;
    left: -300px;
  }
}
.avue-table {
  ::v-deep .el-button--default {
    display: contents;
  }
}
label {
  font-size: 14px;
  margin-left: 16px;
  color: #606266;
}

.dialog-footer {
  height: 52px;
  text-align: right;
  padding: 20px;
}
.confirm-message-wrap {
  word-wrap: break-word;
}
</style>
